const { resolve } = require("path");
//引入html文件打包插件
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
var OptimizeCSSAssetsPlugin = require("optimize-css-assets-webpack-plugin");
const TerserJSPlugin = require("terser-webpack-plugin"); //压缩js
const CssMinimizerPlugin = require("css-minimizer-webpack-plugin"); //压缩css
module.exports = {
  mode: "development", //development(开发环境) production(生产环境)
  //入口文件
  entry: "./src/index.js",
  // 输出路径
  output: {
    filename: "./bundle.js",
    path: resolve(__dirname, "build"),
  },
  //模块解析
  module: {
    rules: [
      //打包css
      {
        test: /\.less$/,
        use: [MiniCssExtractPlugin.loader, "css-loader", "less-loader"],
      },
      {
        test: /\.css$/,
        use: [MiniCssExtractPlugin.loader, "css-loader"],
      },
      //打包图片
      {
        test: /\.(jpg|gif|png|webp)$/,
        use: {
          loader: "url-loader",
          loader: "file-loader",
          options: {
            esModule: false,
            limit: 10 * 1024, //超过10kb就不转成base64
            name: "[name].[ext]",
            outputPath: "images/", //打包到的路径
          },
        },
      },
    ],
  },
  //插件
  plugins: [
    new HtmlWebpackPlugin({
      template: "./src/index.html", //指定模板的文件
      minify: {
        collapseWhitespace: true, //移除空格
        removeComments: true, //移除注释
      },
    }),
    new MiniCssExtractPlugin({
      filename: "css/index.css",
    }),
  ],
  optimization: {
    minimizer: [new CssMinimizerPlugin(), new TerserJSPlugin()],
    minimize: true,
  },
  //开发服务器
  devServer: {
    contentBase: resolve(__dirname, "build"),
    compress: true, //是否压缩
    port: 3000, //服务端口
    open: true, //自动启动游览器
    historyApiFallback: true, //找不到的都可替换为index.html
    proxy: {
      //跨域处理
      "/api": "http://localhost:3000", //接口中有'/api'时代理到'http://localhost:3000'
    },
  },
};
